package org.zjsru.order.task;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.zjsru.order.pojo.Order;
import org.zjsru.order.service.OrderService;
import org.zjsru.order.mapper.OrderMapper;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 订单超时处理定时任务
 */
@Slf4j
@Component
public class OrderTimeoutTask {

    @Autowired
    private OrderService orderService;

    @Autowired
    private OrderMapper orderMapper;

    /**
     * 每小时扫描超时订单
     */
    @Scheduled(fixedRate = 3600000) // 1小时
    public void handleOrderTimeout() {
        log.info("开始扫描超时订单...");
        
        // 查询状态为待支付且创建时间超过30分钟的订单
        LocalDateTime timeoutTime = LocalDateTime.now().minusMinutes(30);
        List<Order> timeoutOrders = orderMapper.findTimeoutOrders(timeoutTime);
        
        for (Order order : timeoutOrders) {
            try {
                orderService.handleOrderTimeout(order.getId());
                log.info("处理超时订单成功，订单ID: {}", order.getId());
            } catch (Exception e) {
                log.error("处理超时订单失败，订单ID: {}", order.getId(), e);
            }
        }
        
        log.info("超时订单扫描完成，共处理 {} 个订单", timeoutOrders.size());
    }
} 